package com.example.medicalzb.controller;

import com.example.medicalzb.domain.Sale;
import com.example.medicalzb.service.SaleService;
import com.example.medicalzb.util.Msg;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;

@RestController
@Api(tags = "销售地点控制器")
@RequestMapping("/api/sales")
@CrossOrigin
public class SaleController {
    @Autowired
    private SaleService saleService;

    @GetMapping(value = {"/{pn}/{size}",""})
    public Msg getSaleWithPage(@PathVariable(value = "pn",required = false) Integer pn,
                               @PathVariable(value = "size",required = false) Integer size,
                               @RequestParam(required = false) String name){
        PageInfo<Sale> pageInfo = saleService.getSaleWithPage(pn,size,name);
        if (pageInfo != null){
            return Msg.success().data("salePageInfo",pageInfo);
        }
        return Msg.fail();
    }

    //根据id查找
    @GetMapping("{id}")
    public Msg getSaleById(@PathVariable("id") Integer id){
        return saleService.getSaleById(id);
    }

    @PostMapping(value = "")
    @RolesAllowed({"1"})
    public Msg saveSale(@RequestBody Sale sale){
        if (sale.getSaleName() != null && sale.getSalePhone() != null){
            return saleService.saveSale(sale);
        }
        return Msg.fail().mess("请将信息填写完整");
    }

    @PutMapping("/{id}")
    @RolesAllowed({"1"})
    public Msg updateSale(@PathVariable("id") Long id,@RequestBody Sale sale){
        if (sale.getSaleName() == null || sale.getSaleName().equals("")){
            return Msg.fail().mess("药店名称不能为空");
        }
        if (sale.getSalePhone() == null || sale.getSalePhone().equals("")){
            return Msg.fail().mess("药店电话不能为空");
        }
        return saleService.updateSale(id,sale);
    }

    @DeleteMapping("/{id}")
    @RolesAllowed({"1"})
    public Msg deleteSale(@PathVariable("id") Long id){
        return saleService.deleteSale(id);
    }

}
